import env from './env';
import Vue from 'vue'

export const Global = {
  isFile: env.isFile, // 判断是否本地环境
  env: env,
  appid: env.appid,
  getAuthorizeUrl() {
    var _href = encodeURI(window.location.href);
    // return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${env.appid}&redirect_uri=${_href}&response_type=code&scope=snsapi_base&state=bosestate`;
    return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx2ced6c77ef5a8d8c&redirect_uri=${_href}&response_type=code&scope=snsapi_userinfo&state=dukangstate#wechat_redirect`;
  },
  page: {
    currentpage: 0,
    pagesize: 10
  },
  uploadType: {
    image: 'image/*"'
  },
  code: {
    
  },
  // 本地环境路径及api配置
  dev: {
    page: {
      index:"index.html",
      account:"account.html",
      activity:"activity.html",
      expensesRecord:"expensesRecord.html",
      gift:"gift.html",
      membershipInterests:"membershipInterests.html",
      rank:"rank.html",
      store:"store.html",
      wine:"wine.html",
      introduction:"introduction.html",
      shopDetail:"shopDetail.html",
      ys:"ys.html",
      customerservice:"customerservice.html"
    },
    api:{
      "memberCenter":'/static/mock/memberCenter.json',// 用户信息
      "getMember":"/static/mock/getMember.json",// 个人中心
      "updateMember":"/static/mock/updateMember.json",//编辑个人信息
      "saveOrUpdateConsigneeInformation":"/static/mock/saveOrUpdateConsigneeInformation.json",//收货地址编辑
      "getNearbyStoresList":"/static/mock/getNearbyStoresList.json",// 附近门店
      "getSignature":"/static/mock/getSignature.json", // 获取授权信息
      "getPurchaseHistoryListByMemberId":"/static/mock/getPurchaseHistoryListByMemberId.json",// 消费记录
    }
  },
  //正式环境路径及api配置
  prod: {
    page: {
      index:"index.html",
      account:"account.html",
      activity:"activity.html",
      expensesRecord:"expensesRecord.html",
      gift:"gift.html",
      membershipInterests:"membershipInterests.html",
      rank:"rank.html",
      store:"store.html",
      wine:"wine.html",
      introduction:"introduction.html",
      shopDetail:"shopDetail.html",
      ys:"ys.html",
      customerservice:"customerservice.html"
    },
    api:{
      "memberCenter":'memberCenter',// 用户信息
      "getMember":'getMember',// 个人中心
      "updateMember":'updateMember',//编辑个人信息
      "saveOrUpdateConsigneeInformation":'saveOrUpdateConsigneeInformation', //收货地址编辑
      "getNearbyStoresList":'getNearbyStoresList',// 附近门店
      "getSignature":'getSignature',// 获取授权信息
      "getPurchaseHistoryListByMemberId":"getPurchaseHistoryListByMemberId",// 消费记录
    }
  },
  getApi(key) {
    var platform = env.isFile ? 'dev' : 'prod';
    let _api = 'http://guoguanglin.cn:8866/dukang/xiaofengtan/' + Global[platform]['api'][key];
    _api = env.isFile ? Global[platform]['api'][key] :_api;
    return _api;
},
  getPage(key, isInterface) { // isInterface外部接口
    var platform = Global.isFile ? 'dev' : 'prod';
    var _url = Global[platform]['page'][key];
    // return isInterface ? env.domain + _url : env.domain + env.rootPage + _url;
    return _url;
  }
}

export const Util = {
  trim(str) {
    return str.replace(/(^\s*)|(\s*$)/g, '');
  },
  storage: {
    set(key, value) {
      window.localStorage.setItem(key, JSON.stringify(value));
    },
    get(key){
      return JSON.parse(window.localStorage.getItem(key) || '[]');
    }
  },
  cookie: {
    addCookie(name, value, path, expiresHours) {
      var cookieString = name + '=' + encodeURIComponent(value);
      //判断是否设置过期时间,0代表关闭浏览器时失效
      if (expiresHours > 0) {
        var date = new Date();
        date.setTime(date.getTime + expiresHours * 3600 * 1000);
        cookieString = cookieString + '; expires=' + date.toGMTString();
      }
      if (path) {
        cookieString = cookieString + ';path=' + path;
      }
      document.cookie = cookieString;
    },
    delCookie(name, path) {
      var date = new Date();
      date.setTime(date.getTime() - 10000); //设定一个过去的时间即可
      document.cookie = name + '=v; expires=' + date.toGMTString();
    },
    getCookie(name) {
      var strCookie = document.cookie;
      var arrCookie = strCookie.split('; ');
      for (var i = 0; i < arrCookie.length; i++) {
        var arr = arrCookie[i].split('=');
        if (arr[0] == name) {
          return arr[1];
        }
      }
      return '';
    }
  },
  numFilter(value) {
    let realVal = Number(value).toFixed(2);
    return realVal;
  },
  isPoneAvailable(str) { // 手机号码验证
    // var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
    var myreg = /^[1][1,2,3,4,5,6,7,8,9][0-9]{9}$/;
    if (!myreg.test(str)) {
      return false;
    } else {
      return true;
    }
  },
  isEmailAvailable(str) { // 邮箱验证
    var myreg = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;
    if (!myreg.test(str)) {
      return false;
    } else {
      return true;
    }
  },
  redirect(key, option, isInterface) {
    var params = Util.parseParam(option);
    if (params) params = '?' + params;
    console.log('redirect',(Global.getPage(key, isInterface) || key) + params)
    window.location.href = (Global.getPage(key, isInterface) || key) + params;
  },
  parseParam(obj) {
    var params = [];
    if (!obj) return '';
    for (var element in obj) {
      if (obj.hasOwnProperty(element)) {
        var value = obj[element];
        params.push(element + '=' + encodeURIComponent(value === null ? '' : String(value)));
      }
    }
    return params.join('&');
  },
  getUrlParam(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
    var r = window.location.search.substr(1).match(reg);
    // console.log(r)
    var _vl = null;
    if (r != null) {
      _vl = unescape(r[2]);
      _vl = decodeURI(decodeURI(_vl))
      return _vl;
    } else {
      return null;
    }


  },
  getUrlAllParam() {
    var obj = new Object();
    if (window.location.search.indexOf("?") == 0 && window.location.search.indexOf("=") > 1) {
      var strs = unescape(window.location.search).substring(1, window.location.search.length).split('&');
      for (var i = 0; i < strs.length; i++) {
        obj[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
      }
    }
    return obj;
  },
  getUrlCode() { // 截取url中的code方法
    var url = location.search
    this.winUrl = url
    var theRequest = new Object()
    if (url.indexOf("?") != -1) {
        var str = url.substr(1)
        var strs = str.split("&")
        for(var i = 0; i < strs.length; i ++) {
            theRequest[strs[i].split("=")[0]]=(strs[i].split("=")[1])
        }
    }
    return theRequest
  },
}

export const Options = {
  createTime: {
    "": "创建时间",
    "desc": "最新发布",
    "asc": "最早发布"
  },
  RefundReason: {
    // "1":"拍错/不喜欢/重复下单",
    "2":"质量问题",
    "3":"描述与商品不符",
    "4":"收到商品少件或破损",
    "5":"其他"
  },
  getOptions(key, isdefault = true) {
    var obj = this[key],
      arr = [];
    for (var item in obj) {
      if (obj.hasOwnProperty(item)) {
        var newItem = {
          value: item,
          title: obj[item],
          key: item,
          ischecked:false
        };
        if (isdefault && newItem.key === '') arr.unshift(newItem);
        else arr.push(newItem);
      }
    }
    return arr;
  }
};

export const Api = {
  _ajax(options) { // ajax请求
    var defaults = {
      key: '',
      url: '',
      contentType: '',
      dataType: 'json',
      type: 'GET',
      data: null
    };
    if (Global.isFile) options.type = 'GET';
    options = Object.assign({}, defaults, options);
    if (!options.url && !options.key) return;
    options.url = options.url || Global.getApi(options.key);
    // var authorization = Util.cookie.getCookie('authorization');
    var _session = Util.storage.get('session')
    if (!options.url) return;
    if (options.type == 'GET' && options.data) {
      options.contentType = 'application/json;charset=UTF-8';
      options.url += '?' + Util.parseParam(options.data) + '&r=' + Math.random();
      options.data = null;
    } else if (arguments.length > 1) {

    } else if (options.type == 'POST') {
      options.contentType = 'application/json;charset=UTF-8';
      options.data = JSON.stringify(options.data);
    }
    var requestTimeout = options.requestTimeout || 3600000;
    var request = this.CreateXMLHttp();
    return new Promise((resolve, reject) => {
      try {
          var requestPath = options.url;
          request.open(options.type, requestPath, true);
          if (options.contentType) request.setRequestHeader("Content-Type", options.contentType);
          if (_session) request.setRequestHeader("JSESSIONID", _session);
          request.timeout = requestTimeout;
          request.send(options.data);
      } catch (err) {
          return reject(err);
      }
      request.onreadystatechange = function () {
          if(request.readyState == 4){
              if(request.status == 200){
                  console.log(request.getAllResponseHeaders())
                  let _header = request.getAllResponseHeaders();
                  if(_header.indexOf("jsessionid") != -1){
                    _header = _header.split(':');
                    let session = _header[_header.length - 1];
                    console.log(session)
                    Util.storage.set('session',session.replace(/(^\s*)|(\s*$)/g, ""))
                    if(session.replace(/(^\s*)|(\s*$)/g, "") == ""){
                      Util.storage.set('userInfo', "");
                      window.location.href = Global.getAuthorizeUrl();
                    }
                  }
                  
                  var update = request.responseText ? JSON.parse(request.responseText) : '';
                  resolve(update)
              }else{
                  Util.storage.set('session',"")
                  Util.storage.set('userInfo', "");
                  window.location.href = Global.getAuthorizeUrl();
                  // return reject(request.status)
              }
          }
          
      };
  });

  },
  upload(options) {
    var formData = new FormData();
    for (var item in options.data) {
      if (options.data.hasOwnProperty(item)) {
        formData.append(item, options.data[item]);
      }
    }
    options.data = formData;
    return this._ajax(options, 'upload');
  },
  CreateXMLHttp() {
    var flag = true;
    var xmlhttp = null;
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      try {
        xmlhttp = ActiveXobject("Msxml12.XMLHTTP");
      } catch (e1) {
        try {
          xmlhttp = ActiveXobject("Microsoft.XMLHTTP");
        } catch (e2) {
          flag = false;
        }
      }
    }
    return xmlhttp;
  },
  go(key, data) { // 对接外部平台
    var _form = document.createElement('form');
    var _body = document.getElementsByTagName('body')[0];
    _form.action = Global.getPage(key, 1);
    _form.method = 'POST';
    for (var item in data) {
      if (data.hasOwnProperty(item)) {
        createHidden(item, data[item]);
      }
    }
    _body.appendChild(_form);
    _form.submit();

    function createHidden(name, value) {
      var _input = document.createElement('input');
      _input.type = 'hidden';
      _input.value = value;
      _input.name = name;
      _form.appendChild(_input);
    }
  },
  ajax(options) {
    var _this = this,
        params = options;
    var promise = this._ajax(options);
    return new Promise((resolve, reject) => {
        promise.then(
        res => {
            console.log('返回值1成功',res)
            resolve(res.data);
        }).catch(res => {
            console.log('catch',res)
            // if (!res) return;
            // if (res.code == Global.code.illegal || res.code == Global.code.illegalToken || res.code == Global.code.errorCodeThree) {
            //     window.location.href = Global.getAuthorizeUrl();
            // } else if (res.code == Global.code.formatError) {
            //     // console.log(res.message);
            // } else if (res.code == Global.code.paramsError) {
            //     // console.log(res.message);
            // } else if (res.code == Global.code.logicError) {
            //     // console.log(res.message);
            // } else if(res.code == Global.code.CarterrorCode || res.code == Global.code.CartStoreerrorCode){
            //     reject(res);
            // }else {
            //     // console.log('系统异常，请联系管理员。');
            //     reject(res);
            // }
            // reject(res);
        });
    });
  }
}

export const on = (function () {
  if (document.addEventListener) {
    return function (element, event, handler) {
      if (element && event && handler) {
        element.addEventListener(event, handler, false);
      }
    };
  } else {
    return function (element, event, handler) {
      if (element && event && handler) {
        element.attachEvent('on' + event, handler);
      }
    };
  }
})();

export const off = (function () {
  if (document.removeEventListener) {
    return function (element, event, handler) {
      if (element && event) {
        element.removeEventListener(event, handler, false);
      }
    };
  } else {
    return function (element, event, handler) {
      if (element && event) {
        element.detachEvent('on' + event, handler);
      }
    };
  }
})();


// 过滤器

// 保留两位小数
Vue.filter("numFilter", function (value) {
  let realVal = Number(value).toFixed(2);
  return realVal;
})
// 保留一位小数
Vue.filter("numOneFilter", function (value) {
  let realVal = Number(value).toFixed(1);
  return realVal;
})
export const TMap = (function (key) {
  return new Promise(function (resolve, reject) {
    window.init = function () {
      resolve(qq) //注意这里
    }
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://map.qq.com/api/js?v=2.exp&callback=init&key=" + key;
    script.onerror = reject;
    document.head.appendChild(script);
  })
})
// 
var fun = function(){
  (function() {
    var hm = document.createElement("script");
    // hm.src = "https://hm.baidu.com/hm.js?282e90bbbe6678d7038dfd7ea70cac7a"; //uat环境
    hm.src = "https://hm.baidu.com/hm.js?6c084a477d374ec829e499ca1f8f88db"; //生产环境
    var s = document.getElementsByTagName("script")[0]; 
    s.parentNode.insertBefore(hm, s);
  })();  
}
fun();
